package com.uzai.console.service.log.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.entity.User;
import com.uzai.common.enums.DeviceTypeEnum;
import com.uzai.common.enums.LogBizTypeEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ESResult;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.log.sysrunlog.SysRunLogQuery;
import com.uzai.console.entity.Device;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.log.SysRunLogService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.log.SysRunLogVo;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 系统运行日志查询
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SysRunLogServiceImpl implements SysRunLogService {

    Logger logger = LoggerFactory.getLogger(SysRunLogServiceImpl.class);

    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;

    /**
     * 查询系统运行日志列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sysRunLogQuery
     * @return null
     */
    public Page<SysRunLogVo> findSysRunLogList(SysRunLogQuery sysRunLogQuery){
        //新建返回到页面的LIST对象
        List<SysRunLogVo> sysRunLogVoList = new ArrayList<>();

        //执行分页查询对象
        Page<SysRunLogVo> page = new Page<>();
        sysRunLogQuery.convert(page);

        //ES查询
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        BoolQueryBuilder boolQuery_or = QueryBuilders.boolQuery();

        //高亮字段
        String highlightField = null;

        //运营商ID
        boolQuery.must(QueryBuilders.termQuery("merId", Tools.getLong(sysRunLogQuery.getMerId())));

        //日志id
        if(StringUtils.isNotBlank(sysRunLogQuery.getTraceid())){
            boolQuery.must(QueryBuilders.termQuery("traceid.keyword", sysRunLogQuery.getTraceid()));
        }

        //设备类型
        if(sysRunLogQuery.getDeviceType() != null){
            boolQuery.must(QueryBuilders.termQuery("deviceType", sysRunLogQuery.getDeviceType()));
        }

        //机器人id
        if(sysRunLogQuery.getDeviceUniqueId() != null){
            boolQuery.must(QueryBuilders.termQuery("deviceUniqueId", sysRunLogQuery.getDeviceUniqueId()));
        }

        //用户id
        if(sysRunLogQuery.getUserId() != null){
            boolQuery.must(QueryBuilders.termQuery("userId", sysRunLogQuery.getUserId()));
        }
        //业务类型
        if(sysRunLogQuery.getBizType() != null){
            boolQuery.must(QueryBuilders.termQuery("bizType", sysRunLogQuery.getBizType()));
        }
        //日志类型
        if(StringUtils.isNotBlank(sysRunLogQuery.getLevel())){
            boolQuery.must(QueryBuilders.termQuery("level.keyword", sysRunLogQuery.getLevel()));
        }

        //查询开始时间
        if(sysRunLogQuery.getQueryStartTime() != null){
            boolQuery.must(QueryBuilders.rangeQuery("logTime").gte(sysRunLogQuery.getQueryStartTime()));
        }

        //查询结束时间
        if(sysRunLogQuery.getQueryEndTime() != null){
            boolQuery.must(QueryBuilders.rangeQuery("logTime").lte(sysRunLogQuery.getQueryEndTime()));
        }

        //微信昵称
        if(StringUtils.isNotBlank(sysRunLogQuery.getMsgInfo())){
            boolQuery.must(QueryBuilders.matchQuery("msgInfo", sysRunLogQuery.getMsgInfo()));
            //highlightField = "msgInfo";
        }

        searchSourceBuilder.query(boolQuery);

        //排序
        if(!sysRunLogQuery.isAsc()){
            searchSourceBuilder.sort("logTime", SortOrder.DESC);
        }else{
            searchSourceBuilder.sort("logTime", SortOrder.ASC);
        }

        try {
            ESResult esResult = elasticsearchUtilGroupMsg.searchListData(EsIndexName.LOGSTASH_API_LOG, searchSourceBuilder, sysRunLogQuery.getSize(), sysRunLogQuery.getFromIndex(), null, null, highlightField, sysRunLogQuery.getMerId());
            page.setTotal(esResult.getTotalHits());
            List<Map<String, Object>> dataList = esResult.getDataList();
            if(dataList != null && dataList.size() > 0){
                for (Map<String, Object> dataMp : dataList) {
                    SysRunLogVo sysRunLogVo  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMp)), SysRunLogVo.class);
                    if(sysRunLogVo != null){
                        //设备型号不为空
                        DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getById(sysRunLogVo.getDeviceType());
                        if(deviceTypeEnum != null) {
                            //机器人信息
                            if(sysRunLogVo.getDeviceUniqueId() != null){
                                Device device = deviceService.findDeviceInfoByDeviceUniqueId(sysRunLogVo.getDeviceUniqueId(), deviceTypeEnum.getKey(), sysRunLogVo.getMerId());
                                if(device != null){
                                    sysRunLogVo.setDeviceName(device.getDeviceName());
                                    sysRunLogVo.setDeviceRemark(device.getDeviceRemark());
                                }
                            }
                        }

                        if(deviceTypeEnum != null){
                            //用户信息
                            if(sysRunLogVo.getUserId() != null){
                                User user = userService.findUserInfo(sysRunLogVo.getUserId(), deviceTypeEnum.getKey(), sysRunLogVo.getMerId());
                                if(user != null){
                                    sysRunLogVo.setUserName(user.getNickName());
                                }
                            }
                        }else{
                            //用户信息
                            if(sysRunLogVo.getUserId() != null){
                                User user = userService.findUserInfo(sysRunLogVo.getUserId(), null, sysRunLogVo.getMerId());
                                if(user != null){
                                    sysRunLogVo.setUserName(user.getNickName());
                                }
                            }
                        }

                        //日志类型名称
                        LogBizTypeEnum logBizTypeEnum = LogBizTypeEnum.getById(sysRunLogVo.getBizType());
                        if(logBizTypeEnum != null){
                            if(!logBizTypeEnum.getValue().equals(logBizTypeEnum.getDesc())){
                                sysRunLogVo.setBizTypeName(logBizTypeEnum.getType() + "-" +logBizTypeEnum.getDesc());
                            }else{
                                sysRunLogVo.setBizTypeName(logBizTypeEnum.getDesc());
                            }
                        }
                        sysRunLogVoList.add(sysRunLogVo);
                    }
                }
            }
        }catch (Exception e){
            logger.error("查询ES账号运行日志出现异常,error={}", e);
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "查询失败");
        }

        //返回到页面分页对象
        page.setRecords(sysRunLogVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return page;
    }
}
